<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>

<script type="text/javascript">
	var jq = jQuery;
</script>
		<script type="text/javascript"
			src="${pageContext.request.contextPath}/jsutils/js/jquery/jquery-ui-1.8.6.custom.min.js"></script>
		<script type="text/javascript"
			src="${pageContext.request.contextPath}/jsutils/js/jqgrid/grid.locale-en.js"></script>
		<script type="text/javascript"
			src="${pageContext.request.contextPath}/jsutils/js/jqgrid/jquery.jqGrid.min.js"></script>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Facturas</title>

	</head>

	<body>


<script type="text/javascript">

var comboProdStr = '<%=pageContext.getSession().getAttribute("productComboList")%>';
var URL = '${pageContext.request.contextPath}/invoices/';
var listMasterURL  = 	URL + 'list';
var saveMasterURL =  	URL + 'save';
var editMasterURL  = 	URL + 'update/';
var deleteMasterURL = 	URL + 'delete/';

var listDetailURL   = URL + "itlist/";
var saveDetailURL   = URL +"saveItem/";
var editDetailURL   = URL + "updateItem/";
var deleteDetailURL = URL + "deleteItem/";
	

	$(function() {

		$.extend($.jgrid.defaults, {
			datatype : 'json',
			jsonReader : {
				repeatitems : false,
				total : function(result) {
					//Total number of pages
					return Math.ceil(result.total / result.max);
				},
				records : function(result) {
					//Total number of records
					return result.total;
				}
			},		
				
			prmNames : {
				rows : 'max',
				search : null
			},
			height : 'auto',
			viewrecords : true,
			rowList : [ 10, 20, 50, 100 ],
			altRows : true,
			loadError : function(xhr, status, error) {
				alert(error);
			}
		});
		
		
		var editOptions = {		    
		    closeAfterEdit : true,
			closeAfterAdd : true,
			ajaxEditOptions : {
				contentType : "application/json"
			},
			mtype : 'PUT',
			serializeEditData : function(data) {
				delete data.oper;
				return JSON.stringify(data);
			},
			onclickSubmit : function(params, postdata) {	
			    		    			
				params.url = editMasterURL + postdata.id;				
			},
			afterSubmit : function(response, postdata) 
				{ 
			        var result = eval('(' + response.responseText + ')');
					var errors = "";
					
			        if (result.success == false) {
						for (var i = 0; i < result.message.length; i++) {
							errors +=  result.message[i] + "<br/>";
						}
			        }  else {
			        	jq("#dialog").text('Entry has been updated successfully');
						jq("#dialog").dialog( 
								{	title: 'Success',
									modal: true,
									buttons: {"Ok": function()  {
										jq(this).dialog("close");} 
									}
								});
	                }
			    	// only used for adding new records
			    	var new_id = null;
			    	
					return [result.success, errors, new_id];
				}
		};
		
		
		var addOptions = {
			closeAfterEdit : true,
			closeAfterAdd : true,
			ajaxEditOptions : {
				contentType : "application/json"
			},
			mtype : 'PUT',
			serializeEditData : function(data) {
				delete data.oper;
				return JSON.stringify(data);
			},
		 
			onclickSubmit : function(params, postdata) {
				params.url = saveMasterURL;
								
			},
			afterSubmit : function(response, postdata) 
				{ 
			        var result = eval('(' + response.responseText + ')');
					var errors = "";
					
			        if (result.success == false) {
						for (var i = 0; i < result.message.length; i++) {
							errors +=  result.message[i] + "<br/>";
						}
			        }  else {
			        	jq("#dialog").text('Entry has been added successfully');
						jq("#dialog").dialog( 
								{	title: 'Success',
									modal: true,
									buttons: {"Ok": function()  {
										jq(this).dialog("close");} 
									}
								});
	                }
			    	// only used for adding new records
			    	var new_id = null;
			    	
					return [result.success, errors, new_id];
				}
		};
		var delOptions = {
		ajaxEditOptions : {
				contentType : "application/json"
			},
			mtype : 'PUT',
			serializeDelData : function(data,postdata) {
				
				return JSON.stringify(data);
			},
 	 onclickSubmit : function(params,postdata) {
				params.url = deleteMasterURL + postdata;				
			}
 	  };
		

	var thisInvoice = 0;
		
		var options = {
			url : listMasterURL,
			height: 100,
			editurl : URL,
			colModel : [ 
				{name:'id', index:'id',formatter:'integer',width: 40,editable: true,editoptions: {disabled: true, size:5}}, 
				{name : 'document',index : 'document',width : 100,editable : true,editrules : {required : true},editoptions : {size : 10}}, 
				{name : 'total',index : 'total',width : 100,editable : true,editrules : {required : true},editoptions : {size : 10}}, 
				{name : 'createdBy',index : 'createdBy',width : 100,editable : true, editoptions: {disabled:true, size:10} }, 
				{name : 'createdOn',index : 'createdOn',width : 100,editable : true, editoptions: {disabled:true, size:10} }, 
				{name : 'modifiedBy',index : 'modifiedBy',width : 100,editable: false}, 
				{name : 'modifiedOn',index : 'modifiedOn',width : 100,editable : false} 
				],
			caption : "Invoices",
			pager : '#pager',
			height : 'auto',
			ondblClickRow : function(id) {
				jQuery(this).jqGrid('editGridRow', id, editOptions);
			},
			
			onSelectRow: function(ids) {
                    if (ids != null) {
                        //var data = $("#list").getRowData(ids);
                        thisInvoice = ids;                        
                        jQuery("#grid_det").setGridParam({ url: listDetailURL + ids, page: 1 })
               .setCaption("<b>Items para factura : " + ids +"</b>")
               .trigger('reloadGrid');
                    }
                }
			
		};

		$("#grid").jqGrid(options);
		jQuery("#grid").navGrid(
			'#pager', 
			{search:false}, //options
			editOptions, 
			addOptions, 
			delOptions, 
			{} // search options
		);
		
		
/*-- -------------------------------------------- tabla detalle ----------------------------------------------- -- */

var editDetailOptions = {		    
		    closeAfterEdit : true,
			closeAfterAdd : true,
			ajaxEditOptions : {
				contentType : "application/json"
			},
			mtype : 'PUT',
			serializeEditData : function(data) {
				delete data.oper;
				return JSON.stringify(data);
			},
			onclickSubmit : function(params, postdata) {			    							
				params.url = editDetailURL;				
			},
			afterSubmit : function(response, postdata) 
				{ 
			        var result = eval('(' + response.responseText + ')');
					var errors = "";
					
			        if (result.success == false) {
						for (var i = 0; i < result.message.length; i++) {
							errors +=  result.message[i] + "<br/>";
						}
			        }  else {
			        	jq("#dialog").text('Entry has been updated successfully');
						jq("#dialog").dialog( 
								{	title: 'Success',
									modal: true,
									buttons: {"Ok": function()  {
										jq(this).dialog("close");} 
									}
								});
	                }
			    	// only used for adding new records
			    	var new_id = null;
			    	
					return [result.success, errors, new_id];
				}
		};		     		     
	     
		     
var addDetailOptions = {
			closeAfterEdit : true,
			closeAfterAdd : true,
			ajaxEditOptions : {
				contentType : "application/json"
			},
			mtype : 'PUT',
			serializeEditData : function(data) {
				delete data.oper;
				return JSON.stringify(data);
			},
			
			afterShowForm : function (formid) {			    
			 	$("#invoiceId",formid).val(thisInvoice);
			    $("#tr_invoiceId",formid).hide();			    			    
			    
		    }, 
		 
			onclickSubmit : function(params, postdata, formid) {	
				$("#invoiceId",formid).show();					    
				params.url = saveDetailURL;											
			},
			afterSubmit : function(response, postdata) 
				{ 
			        var result = eval('(' + response.responseText + ')');
					var errors = "";
					
			        if (result.success == false) {
						for (var i = 0; i < result.message.length; i++) {
							errors +=  result.message[i] + "<br/>";
						}
			        }  else {
			        	jq("#dialog").text('Entry has been added successfully');
						jq("#dialog").dialog( 
								{	title: 'Success',
									modal: true,
									buttons: {"Ok": function()  {
										jq(this).dialog("close");} 
									}
								});
	                }
			    	// only used for adding new records
			    	var new_id = null;
			    	
					return [result.success, errors, new_id];
				}
};


var delDetailOptions = {
		ajaxEditOptions : {
				contentType : "application/json"
			},
			mtype : 'PUT',
			serializeDelData : function(data,postdata) {
				
				return JSON.stringify(data);
			},
 	 onclickSubmit : function(params,postdata) {
				params.url = deleteDetailURL + postdata;				
			}
 	  };
 	  
 


var options_det = {
			url : listDetailURL + "0" ,
			height: 100,
			editurl : URL,
			colModel : [ 
				  {name:'id', label: 'id',formatter:'integer',width: 100,editable: true,editoptions: {disabled: true, size:5}},
				  {name: 'invoiceId', index: 'invoiceId', label:'Id Factura', width: 100, align: 'left',editable: true, editoptions: {disabled: true, size:5} },
				  {name: 'productId', index: 'productId', label:'Producto', 
				  			width: 100, align: 'left',editable: true, 
				  			edittype:"select", 
                  			editoptions:{value: comboProdStr} 
                  			},
                  {name: 'productName', index: 'productName', width: 100, align: 'left',editable: true, editable:false },
                  
                  {name: 'invoiceDoc', index: 'invoiceDoc', width: 100, align: 'left',editoptions: {disabled:true, size:10} },                  
                  {name: 'quantity', index: 'quantity', width: 100, align: 'left',editable: true },
                  {name: 'cost', index: 'cost', width: 100, align:'left',editable: true},                                   
                  {name: 'createdBy', index: 'createdBy', width: 100, align: 'left' , editable:true, editoptions: {disabled:true, size:10}},
                  {name: 'createdOn', index: 'createdOn', width: 100, align: 'left' , editable:true, editoptions: {disabled:true, size:10}},                  
                  {name : 'modifiedBy',index : 'modifiedBy',width : 100,editable: false}, 
				  {name : 'modifiedOn',index : 'modifiedOn',width : 100,editable : false},                   
				],
			caption : "Items",
			pager : '#pager_det',
			height : 'auto',
			ondblClickRow : function(id) {
				jQuery(this).jqGrid('editGridRow', id, editDetailOptions);
			}			
		};
		
		
		
		$("#grid_det").jqGrid(options_det);
            /*agregando botones a la barra de navegacion*/
            $("#grid_det").navGrid(
            	"#pager_det", 
            	{search:false},//options            	
		        editDetailOptions,//edit
		        addDetailOptions,//add
		        delDetailOptions,//del
		        {}
		     );


	     
		     
		     
/*formas detail*/

		/*-- ------------------------------------------------- --*/

		
	});//function-ready
</script>

		<p>
			Facturas
		</p>
		<div id="jqgrid">
			<table id="grid"></table>
			<div id="pager"></div>
		</div>
		<br/>
		
		<div id="jqgrid_det">
			<table id="grid_det"></table>
			<div id="pager_det"></div>
		</div>
		

		<div id="dialog" title="Feature not supported" style="display: none">
			<p>
				That feature is not supported.
			</p>
		</div>

		<div id="dialogSelectRow" title="Warning" style="display: none">
			<p>
				Please select row
			</p>
		</div>

	</body>

</html>